#!/bin/bash
#
# Copyright (c) Citrix Systems 2008. All rights reserved.
#
#   ./repeat n operation vm_name optional_args
#

if [ $# -ne 2 ]; then 
   echo "Usage: $0 n vm_name"
   echo "Starts VMs nammed vm_name<1> .. vm_name<n> and output the time taken and the load average."
   echo "if WAIT_FOR_IP is set to 1, then wait the IP address to appear before starting the next VM. need xgetip executable to be in the current directory."
   exit 1
fi 

N=$1
VM_NAME=$2

MASTER=`xe pool-list params=master --minimal`
START=$(date +%s)

wait_IP () {
    i=$1
    VM_UUID=`xe vm-list name-label=${VM_NAME}${i} params=uuid --minimal`
    MAC=`xe vif-list vm-uuid=${VM_UUID} params=MAC --minimal`
    echo "Waiting for the IP address of ${VM_NAME}${i} to appear."
    IP=`./xgetip xenbr0 ${MAC} &> /dev/null`
    echo "IP address of ${VM_NAME}${i} is ${IP}."
}

echo "# vm_number cumulative_time load_average"

perform () {
    i=$1
    TMP=`xe vm-start vm=${VM_NAME}${i}`
    if [ "${WAIT_FOR_IP}" == "1" ]; then
	wait_IP ${i}
    fi
    CURR=$(date +%s)
    DIFF=$(( ${CURR} - ${START} ))
    LOADAVG=`xe host-data-source-query data-source=loadavg host=${MASTER}`
    echo "${i} ${DIFF} ${LOADAVG}" 
}

for i in `seq 1 ${N}`; do 
    perform $i
done
